var express = require('express');
var router = express.Router();
const db = require("../model/db")

//查询所有供货商 
router.get("/", async (req, res) => {
    if (!req.query.field) {
        req.query.field = "_id";//默认按照id排序
    }
    if (!req.query.sort) {
        req.query.sort = "asc";//默认按照升序排序
    }
    //拼接排序字符串
    let s = req.query.field;
    if (req.query.sort === "desc") {
        s = "-" + s;
    }
    // 分页
    if (!req.query.page) {
        req.query.page = 1;//页索引
    }
    if (!req.query.limit) {
        req.query.limit = 10;//页容量
    }
    const page = parseInt(req.query.page);
    const limit = parseInt(req.query.limit);
    let condition = {};
    if (req.query.key) {
        const exp = new RegExp(req.query.key, "i")//不区分大小写，模糊查询的正则表达式
        condition = {
            $or: [
                { name: { $regex: exp } },
                { address: { $regex: exp } }
            ]
        };
    }
    const data = await db.Supplier.find(condition).sort(s).skip((page - 1) * limit).limit(limit);
    const count = await db.Supplier.countDocuments(condition);
    res.send({
        code: 0,
        message: "",
        count,
        data
    });
})

// 添加供货商
router.post("/", async (req, res) => {
    const data = await db.Supplier.create(req.body);
    res.send({
        code: 0,
        message: "",
        data
    });
})

//查询单个供货商
router.get('/:id', async (req, res) => {
    const data = await db.Supplier.findById(req.params.id);
    res.send({
        code: 0,
        message: "",
        data
    })
});

// 删除单个供货商
router.delete("/:id", async (req, res) => {
    await db.Supplier.deleteOne({
        _id: req.params.id
    });
    res.send(true);
});

// 修改单个供货商
router.put("/:id", async (req, res) => {
    await db.Supplier.updateOne({
        _id: req.params.id
    }, req.body);
    res.send(true);
})



module.exports = router;
